/*
 * @(#)AuthorityManager.java
 * 2011-6-8 上午12:02:23
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.qyxx.jwp.bean.Button;
import com.qyxx.jwp.bean.Field;
import com.qyxx.jwp.bean.Form;
import com.qyxx.jwp.menu.Business;
import com.qyxx.jwp.menu.Menu;
import com.qyxx.jwp.menu.Module;
import com.qyxx.jwp.menu.Modules;
import com.qyxx.platform.common.definition.Definition.DefinitionEntity;
import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.encode.EncodeUtils;
import com.qyxx.platform.common.utils.encode.FontConvertUtils;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.sysmng.accountmng.dao.AuthorityDao;
import com.qyxx.platform.sysmng.accountmng.dao.AuthorityLocaleDao;
import com.qyxx.platform.sysmng.accountmng.dao.OrganizationDao;
import com.qyxx.platform.sysmng.accountmng.dao.RoleDao;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.accountmng.entity.Authority;
import com.qyxx.platform.sysmng.accountmng.entity.AuthorityJson;
import com.qyxx.platform.sysmng.accountmng.entity.AuthorityLocale;
import com.qyxx.platform.sysmng.accountmng.entity.Organization;
import com.qyxx.platform.sysmng.accountmng.entity.ResourceJson;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.accountmng.entity.UserJson;
import com.qyxx.platform.sysmng.dictmng.web.DefinitionCache;
import com.qyxx.platform.sysmng.utils.Constants;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion.Static;

/**
 * 资源权限Manager类
 * 
 * @author gxj
 * @version 1.0
 * @since 1.6 2011-6-8 上午12:02:23
 */
@Service
@Transactional
public class AuthorityManager {
	private AuthorityDao authorityDao;

	private AuthorityLocaleDao authorityLocaleDao;

	private RoleDao roleDao;

	private UserDao userDao;

	private OrganizationDao organizationDao;
	
	private ResourceCacheService resourceCacheService;

	private static final String FIND_MENU_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.ResourceJson(b, a.resourceName) "
			+ " from AuthorityLocale a inner join a.authority b inner join b.roleList c where"
			+ " c.id in (select e.id from User d inner join d.roleList e where d.id = ?)"
			+ " and b.resourceType = ? and a.resourceLocale = ? and b.resourceStatus = ?  and b.appShow = ?"
			+ " order by b.resourceLevel asc, b.resourceNo asc";
	
	private static final String FIND_APP_MENU_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.ResourceJson(b, a.resourceName) "
			+ " from AuthorityLocale a inner join a.authority b inner join b.roleList c where"
			+ " c.id in (select e.id from User d inner join d.roleList e where d.id = ?)"
			+ " and b.resourceType = ? and a.resourceLocale = ? and b.resourceStatus = ? and b.appShow = ?"
			+ " order by b.resourceLevel asc, b.resourceNo asc";

	private static final String FIND_LIST_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.AuthorityJson(a.id, a.resourceName, a.authority.id, a.resourceType, a.resourceStatus)"
			+ " from Authority a where a.resourceStatus = ? order by a.resourceLevel asc, a.resourceNo asc";
	
	//查询角色查找拥有权限
	private static final String FIND_ROLE_HAS_AUTH_HQL = "select distinct a.id from Authority a inner join a.roleList c where c.id = ?";
	
	private static final String FIND_ALL_AUTH_LIST_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.AuthorityJson(a.id, a.resourceName, a.authority.id, a.resourceType, a.resourceStatus)"
		+ " from Authority a order by a.resourceLevel asc, a.resourceNo asc";

	private static final String FIND_AUT_LIST_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.AuthorityJson(a.id, a.resourceName, a.authority.id, a.resourceType, a.resourceStatus)"
			+ " from Authority a inner join a.roleList c inner join c.organization d where"
			+ " d.id in (select f.id from User e inner join e.organization f  where e.id = ?)"
			+ " and a.resourceStatus = ? order by a.resourceLevel asc, a.resourceNo asc";

	private static final String FIND_USER_LIST_HQL = "select new com.qyxx.platform.sysmng.accountmng.entity.UserJson(a)"
			+ " from User a inner join a.organization b where b.organizationCode like ? ";
	
	private static final String FIND_AUTH_BY_NAME_HQL = "from Authority a where a.name = ? and a.resourceType = ? and a.resourceStatus = ? and a.resourceLevel = ?";
	
	private static final String FIND_AUTH_BY_URL_HQL = "from Authority a where a.resourceUrl = ? and a.resourceType = ? and a.resourceStatus = ? ";

	private static final String DELETE_AUTHORITY_LOCALE = "delete from AuthorityLocale a where a.authority.id = ? ";
	
	private static final String FIND_RESOURCE_URL_BY_SQL = "select  DISTINCT RESOURCE_URL "
			+ "from  sys_user_to_role a,sys_resource_to_role  b, SYS_RESOURCE c "
            +"where USER_ID = ?  and  a.ROLE_ID = b.ROLE_ID and  b.RESOURCE_ID = c.ID";
	/**
	 * @param authorityDao
	 */
	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}

	@Autowired
	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	/**
	 * @param authorityLocaleDao
	 */
	@Autowired
	public void setAuthorityLocaleDao(
			AuthorityLocaleDao authorityLocaleDao) {
		this.authorityLocaleDao = authorityLocaleDao;
	}
	
	@Autowired
	public void setResourceCacheService(
			ResourceCacheService resourceCacheService) {
		this.resourceCacheService = resourceCacheService;
	}

	/**
	 * 根据用户查找对应的菜单资源
	 * 
	 * @param userId
	 * @return
	 */
	public List<ResourceJson> findMenuResource(Long userId,
			String locale) {
		List<Object> paramList = Lists.newArrayList();
		paramList.add(userId);
//		paramList.add(Constants.RESOURCE_LEVEL_1);
//		paramList.add(Constants.RESOURCE_LEVEL_2);
//		paramList.add(Constants.RESOURCE_LEVEL_3);
		paramList.add(Constants.RESOURCE_TYPE_MENU);
		paramList.add(locale);
		paramList.add(Constants.ENABLED);
		paramList.add(false);
		List<ResourceJson> list = authorityLocaleDao.find(
				FIND_MENU_HQL, paramList.toArray());

		// 去除重复项
		Set<ResourceJson> set = new HashSet<ResourceJson>();
		List<ResourceJson> newList = new ArrayList<ResourceJson>();
		Map<Long, ResourceJson> tmpMap = new HashMap<Long, ResourceJson>();
		
		for (Iterator<ResourceJson> iter = list.iterator(); iter
				.hasNext();) {
			ResourceJson element = iter.next();
			if (set.add(element)) {
				newList.add(element);
				tmpMap.put(element.getId(), element);
			}
		}
		list.clear();
		list.addAll(newList);

		Map<Long, ResourceJson> map = new HashMap<Long, ResourceJson>();
		if (null != list) {
			for (ResourceJson rj : list) {
				if (rj.getParentId() == null) {
					map.put(rj.getId(), rj);
				} else {
					ResourceJson t = tmpMap.get(rj.getParentId());
					if (t != null) {
						t.getChilds().add(rj);
					}
				}
			}
		}
		List<ResourceJson> rjList = new ArrayList<ResourceJson>(
				map.values());
		Collections.sort(rjList, new Comparator<ResourceJson>() {

			public int compare(ResourceJson o1, ResourceJson o2) {
				if (o1.getResourceNo() > o2.getResourceNo()) {
					return 1;
				} else if (o1.getResourceNo() < o2.getResourceNo()) {
					return -1;
				} else {
					return 0;
				}
			}
		});
		return rjList;
	}

	/**
	 * 根据用户ID和角色ID来查找相应权限列表
	 */
	public List<AuthorityJson> getAuthorityList(Long id) {
		List<Object> paramList = Lists.newArrayList();
		paramList.add(Constants.IS_USING);
		List<AuthorityJson> list = authorityDao.find(FIND_LIST_HQL,
				paramList.toArray());
		/*
		Set<AuthorityJson> set = new HashSet<AuthorityJson>();
		List<AuthorityJson> newList = new ArrayList<AuthorityJson>();
		for (Iterator<AuthorityJson> iter = list.iterator(); iter
				.hasNext();) {
			AuthorityJson element = iter.next();
			if (set.add(element)) {
				newList.add(element);
			}
		}
		list.clear();
		list.addAll(newList);*/

		if (id != null) {
			Role role = roleDao.get(id);
			List<Authority> selectList = role.getAuthorityList();
			Long b = 0L;
			for (int i = 0; i < selectList.size(); i++) {
				b = selectList.get(i).getId();
				for (int j = 0; j < list.size(); j++) {
					if (b == list.get(j).getId()) {
						list.get(j).setChecked(true);
					}
				}
			}
			return list;
		}
		return list;
	}
	
	/**
	 * 查询所有资源，用于树形结构展现
	 */
	public List<AuthorityJson> getAuthorityList() {
		List<AuthorityJson> list = authorityDao.find(FIND_ALL_AUTH_LIST_HQL);
		return list;
	}
	
	/**
	 * 根据角色Id查找拥有权限ID
	 * 
	 * @param roleId
	 * @return
	 */
	public List<Long> getRoleAuthorityId(Long roleId) {
		return authorityDao.find(FIND_ROLE_HAS_AUTH_HQL, roleId);
	}

	/**
	 * 根据用户ID来查找对应角色拥有的权限列表
	 */

	public List<AuthorityJson> getUserAuthorityList(Long userId,Long id) {
		List<Object> paramList = Lists.newArrayList();
		paramList.add(userId);
		//paramList.add(Constants.NO_USING);
		paramList.add(Constants.IS_USING);
		List<AuthorityJson> list = authorityDao.find(
				FIND_AUT_LIST_HQL, paramList.toArray());

		Set<AuthorityJson> set = new HashSet<AuthorityJson>();
		List<AuthorityJson> newList = new ArrayList<AuthorityJson>();
		for (Iterator<AuthorityJson> iter = list.iterator(); iter
				.hasNext();) {
			AuthorityJson element = iter.next();
			if (set.add(element)) {
				newList.add(element);
			}
		}
		list.clear();
		list.addAll(newList);
		
		if (id != null) {
			Role role = roleDao.get(id);
			List<Authority> selectList = role.getAuthorityList();
			Long b = 0L;
			for (int i = 0; i < selectList.size(); i++) {
				b = selectList.get(i).getId();
				for (int j = 0; j < list.size(); j++) {
					if (b == list.get(j).getId()) {
						list.get(j).setChecked(true);
					}
				}
			}
			return list;
		}
		return list;

	}

	/**
	 * 根据部门ID来查找其拥有的用户列表
	 */

	public List<UserJson> getUserList(Long r_id, Long orgId) {
		Organization organization = organizationDao.get(orgId);
		String org_code = organization.getOrganizationCode();
		List<Object> paramList = Lists.newArrayList();
		paramList.add(org_code+"%");
		List<UserJson> list = userDao.find(FIND_USER_LIST_HQL,
				paramList.toArray());// 查询到该组织以及子组织下所有的USER用户
	
		/*List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter idFilter = new PropertyFilter(
				"LIKES_organizationCode", org_code + "%");
		filters.add(idFilter);
		List<Organization> orgList = organizationDao.find(filters);// 查询到该组织下的所有子组织

		for (int i = 0,l=orgList.size(); i < l; i++) {
			Organization org = orgList.get(i);
			UserJson userJson = new UserJson(org.getId(), org, org.getOrganizationName(),true,false);
			list.add(userJson);
		}*/
		

		if (r_id != null) {
			List<User> selectList = roleDao.get(r_id).getUserList();

			Long b = 0L;
			for (int i = 0; i < selectList.size(); i++) {
				b = selectList.get(i).getId();
				for (int j = 0; j < list.size(); j++) {
					if (b == list.get(j).getUserId()) {
						list.get(j).setChecked(true);
					}
				}
			}
		}
		return list;

	}
	
	/**
	 * 根据部门ID查询部门用户树
	 * 
	 * @param orgId
	 * @return
	 */
	public List<UserJson> getUserTree(Long orgId) {
		Organization organization = organizationDao.get(orgId);
		String org_code = organization.getOrganizationCode();
		List<Object> paramList = Lists.newArrayList();
		paramList.add(org_code+"%");
		List<UserJson> list = userDao.find(FIND_USER_LIST_HQL,
				paramList.toArray());// 查询到该组织以及子组织下所有的USER用户
	
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter idFilter = new PropertyFilter(
				"LIKES_organizationCode", org_code + "%");
		filters.add(idFilter);
		List<Organization> orgList = organizationDao.find(filters);// 查询到该组织下的所有子组织

		for (int i = 0,l=orgList.size(); i < l; i++) {
			Organization org = orgList.get(i);
			UserJson userJson = new UserJson(org.getId(), org, org.getOrganizationName(),true,false);
			list.add(userJson);
		}
		
		return list;
	}
	
	/**
	 * 获取角色可见用户列表
	 * 
	 * @param roleId
	 * @param orgId
	 * @return
	 */
	public List<UserJson> getSeeUserList(Long roleId, Long orgId) {
		Organization organization = organizationDao.get(orgId);
		String org_code = organization.getOrganizationCode();
		List<Object> paramList = Lists.newArrayList();
		paramList.add(org_code+"%");
		List<UserJson> list = userDao.find(FIND_USER_LIST_HQL,
				paramList.toArray());// 查询到该组织以及子组织下所有的USER用户
	
		/*List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter idFilter = new PropertyFilter(
				"LIKES_organizationCode", org_code + "%");
		filters.add(idFilter);
		List<Organization> orgList = organizationDao.find(filters);//查询到该组织下的所有子组织

		for (int i = 0,l=orgList.size(); i < l; i++) {
			Organization org = orgList.get(i);
			UserJson userJson = new UserJson(org.getId(), org, org.getOrganizationName(),true,false);
			list.add(userJson);
		}*/
		

		if (roleId != null) {
			List<User> selectList = roleDao.get(roleId).getSeeUserList();
			Long b = 0L;
			for (int i = 0; i < selectList.size(); i++) {
				b = selectList.get(i).getId();
				for (int j = 0; j < list.size(); j++) {
					if (b == list.get(j).getUserId()) {
						list.get(j).setChecked(true);
					}
				}
			}
		}
		return list;
	}

	/**
	 * 查询资源列表
	 */
	@Transactional(readOnly = true)
	public Page<Authority> findResourceList(Page<Authority> page,
			List<PropertyFilter> filters) {
		return authorityDao.findPage(page, filters);
	}

	/**
	 * 获取资源对象
	 */
	@Transactional(readOnly = true)
	public Authority getAuthority(Long id) {
		Authority authority = authorityDao.get(id);
		List<AuthorityLocale> list = authorityLocaleDao.findBy(
				"authority.id", id);
		Map<String, AuthorityLocale> localeMap = new HashMap<String, AuthorityLocale>();
		if (list.size() > 0) {
			for (AuthorityLocale al : list) {
				localeMap.put(al.getResourceLocale(), al);
			}
		}
		authority.setLocaleMap(localeMap);
		return authority;
	}

	/**
	 * 保存资源
	 */
	public void saveResource(Authority a,Long parentId,Map m) {
		// 添加资源信息
		if (parentId != null) {
			Authority parentAuthority = authorityDao.get(parentId);
			a.setAuthority(parentAuthority);
		}
		User user = (User) Struts2Utils
				.getSessionAttribute(Constants.USER_SESSION_ID);
		Long userId = user.getId();
		Long aId = a.getId();
    	if(null!=aId) {//修改
    		a.setLastUpdateTime(new Date());
    		a.setLastUpdateUser(userId);
    	} else {//新增
    		a.setCreateTime(new Date());
        	a.setCreateUser(userId);
    	}
		authorityDao.save(a);

		// 添加资源国际信息
		Long id = null;
		for (Object obj : m.keySet()) {
			String locale = String.valueOf(obj);
			String resourceName = String.valueOf(m.get(obj));
			if (locale.indexOf("-") >= 0 && locale.indexOf("-") != -1) {
				String s[] = locale.split("-");
				id = Long.valueOf(s[1]);
			}
			if (id == null) {
				AuthorityLocale newLocale = new AuthorityLocale();
				newLocale.setAuthority(a);
				newLocale.setResourceName(resourceName);
				newLocale.setResourceLocale(locale);
				authorityLocaleDao.save(newLocale);
			} else {
				AuthorityLocale oldLocale = authorityLocaleDao
						.get(id);
				oldLocale.setResourceName(resourceName);
			}
		}
		
		//新增资源后授权超级管理员角色
		if(aId == null) {
			authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, a.getId());
		}

	}

	/**
	 * 删除资源
	 */
	public void deleteAuthority(Long id) {
		Authority authority = this.getAuthority(id);
		authority.setResourceStatus(Constants.IS_DELETE);
		Long pid = authority.getId();
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter filter = new PropertyFilter("EQL_authority.id", String.valueOf(pid));		
		filters.add(filter);
		List<Authority> childAuthority = authorityDao.find(filters);		
		for(Authority a : childAuthority){
			this.deleteAuthority(a.getId());
		}
		
	}
	/**
	 * 彻底删除资源
	 * 
	 * @param AuthorityID id
	 */
	public void shiftDeleteAuthority(Long id) {
		Authority authority = this.getAuthority(id);
		
		if(Constants.IS_DELETE.equals(authority.getResourceStatus())){//只有在'已删除'的状态下才能进行侧地删除
		Long pid = authority.getId();
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter filter = new PropertyFilter("EQL_authority.id", String.valueOf(pid));		
		filters.add(filter);
		List<Authority> childAuthority = authorityDao.find(filters);		
		for(Authority a : childAuthority){//删除当前资源下的所有子资源	
			this.shiftDeleteAuthority(a.getId());
			}	
		authorityDao.delete(id);//删除资源表里面的记录
		authorityDao.deleteByResourceId(id);//删除资源和角色关联表里面的记录
		authorityLocaleDao.batchExecute(DELETE_AUTHORITY_LOCALE, id);//删除资源国际化表里面的记录
		
		}

	}
	/**
	 * 恢复资源
	 * @param AuthorityID id
	 */
	public void recoverAuthority(Long id) {
		Authority authority = this.getAuthority(id);
		authority.setResourceStatus(Constants.IS_USING);
		Long pid = authority.getId();
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		PropertyFilter filter = new PropertyFilter("EQL_authority.id", String.valueOf(pid));		
		filters.add(filter);
		List<Authority> childAuthority = authorityDao.find(filters);		
		for(Authority a : childAuthority){
			this.recoverAuthority(a.getId());
		}
	}
	
	/**
	 * 对Module进行添加或修改权限
	 * 
	 * @param mdList
	 * @param mdsAuth
	 * @param fieldFormMap
	 * @param level
	 * @param buttonMap
	 * 
	 */
	public void handleModuleResource(List<Module> mdList,Authority mdsAuth,Map<String, List<Form>> fieldFormMap,
			long level, Map<String, List<Button>> buttonMap, Boolean isFullUpdate, List<String> updatedModules) {
		if(null!=mdList && !mdList.isEmpty()) {
			long mdOrder = 1L;
			for(Module md : mdList) {
				if(com.qyxx.jwp.menu.Module.TYPE_MODULES.equals(md.getType())){
					if(null!=md.getModule()&& !md.getModule().isEmpty()){
						//业务模块集合
						String mdsKey = Authority.RESOURCE_PREFIX + md.getKey().toUpperCase();
						Authority mdsAuth1 = authorityDao.findUnique(FIND_AUTH_BY_NAME_HQL, mdsKey, 
								Constants.RESOURCE_TYPE_MENU, Constants.ENABLED, String.valueOf(level));
						if(null!=mdsAuth1) {
							//修改数据
							String mdsName = md.getName();
							if(!mdsName.equals(mdsAuth1.getResourceName())) {
								//修改国际化语言支持
								modifyAuthLocale(mdsAuth1.getId(), mdsName, md.getKey());
							}
							mdsAuth1.setResourceName(md.getName());
							mdsAuth1.setResourceNo(mdOrder++);
							mdsAuth1.setResourceIcon(md.getIconSkin());
							mdsAuth1.setLastUpdateTime(new Date());
							mdsAuth1.setAuthority(mdsAuth);
						} else {
							//新增数据
							mdsAuth1 = new Authority();
							mdsAuth1.setName(mdsKey);
							mdsAuth1.setResourceName(md.getName());
							mdsAuth1.setLogRule(md.getName());
							mdsAuth1.setResourceType(Constants.RESOURCE_TYPE_MENU);
							mdsAuth1.setResourceStatus(Constants.ENABLED);
							mdsAuth1.setResourceLevel(String.valueOf(level));
							mdsAuth1.setResourceUrl("");
							mdsAuth1.setResourceNo(mdOrder++);
							mdsAuth1.setResourceIcon(md.getIconSkin());
							mdsAuth1.setCreateTime(new Date());
							mdsAuth1.setAuthority(mdsAuth);
							authorityDao.save(mdsAuth1);
							//授权超级管理员角色
							authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, mdsAuth1.getId());
							//增加国际化语言支持
							saveAuthLocale(mdsAuth1, md.getKey());
						}
						 handleModuleResource(md.getModule(), mdsAuth1, fieldFormMap,level+1, buttonMap, isFullUpdate, updatedModules);
						 if(com.qyxx.jwp.menu.Module.TYPE_APPS.equals(md.getType())){
							 mdsAuth1.setAppShow(true);
						 }else{
							 mdsAuth1.setAppShow(false);
						 }
					} 			
				}else{
					//增量更新判断是否需要更新模块
					if(!isFullUpdate && !updatedModules.contains(md.getKey())) {
						mdOrder++;
						continue;
					}
					Boolean isAppShow;
					if(com.qyxx.jwp.menu.Module.TYPE_APP.equals(md.getType())){							
						isAppShow=true;
					}else{
						isAppShow=false;
					}
					
					
					String mdKey = Authority.RESOURCE_PREFIX + md.getKey().toUpperCase();
					String entityName = md.getEntityName();
					String mdUrl = Constants.RESOURCE_QUERY_URL + entityName;
					String mdName = md.getName();
					Authority mdAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, mdUrl, 
							Constants.RESOURCE_TYPE_MENU, Constants.ENABLED);
					if(null!=mdAuth) {
						if(!mdName.equals(mdAuth.getResourceName())) {
							//修改国际化语言支持
							modifyAuthLocale(mdAuth.getId(), mdName, md.getKey());
						}
						mdAuth.setResourceName(mdName);
						mdAuth.setName(mdKey);
						mdAuth.setLogRule(mdName);
						mdAuth.setResourceNo(mdOrder++);
						mdAuth.setResourceIcon(md.getIconSkin());
						mdAuth.setLastUpdateTime(new Date());
						mdAuth.setResourceLevel(String.valueOf(level));
						mdAuth.setAuthority(mdsAuth);						
					    mdAuth.setAppShow(isAppShow);
					} else {
						//新增数据
						mdAuth = new Authority();
						mdAuth.setName(mdKey);
						mdAuth.setResourceName(mdName);
						mdAuth.setLogRule(mdName);
						mdAuth.setResourceType(Constants.RESOURCE_TYPE_MENU);
						mdAuth.setResourceStatus(Constants.ENABLED);
						mdAuth.setResourceLevel(String.valueOf(level));
						mdAuth.setResourceUrl(mdUrl);
						mdAuth.setResourceNo(mdOrder++);
						mdAuth.setResourceIcon(md.getIconSkin());
						mdAuth.setCreateTime(new Date());
						mdAuth.setAuthority(mdsAuth);						
						mdAuth.setAppShow(isAppShow);
						authorityDao.save(mdAuth);
						//授权超级管理员角色
						authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, mdAuth.getId());
						//增加国际化语言支持
						saveAuthLocale(mdAuth, md.getKey());
					}
					//增加模块按钮
					long level1 = level + 1;
					long authOrder = 1L;
					String[] rbu = Constants.RESOURCE_BT_URL;
					for(int i=0,len=rbu.length; i<len; i++) {
						String btUrl = rbu[i] + entityName;
						String btName = mdName + Constants.MINUS + Constants.RESOURCE_BT_NAME[i];
						String ruleName = mdName + Constants.MINUS + Constants.RESOURCE_BT_RULE[i];
						String btKey = mdKey + Constants.UNDERLINE + Constants.RESOURCE_BT_KEY[i];
						Authority btAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, btUrl, 
								Constants.RESOURCE_TYPE_BUTTON, Constants.ENABLED);
						if(null!=btAuth) {
							btAuth.setResourceName(btName);
							btAuth.setName(btKey);
							btAuth.setLogRule(ruleName);
							btAuth.setResourceNo(authOrder++);
							btAuth.setLastUpdateTime(new Date());
							btAuth.setResourceLevel(String.valueOf(level1));
							btAuth.setAuthority(mdAuth);
							btAuth.setAppShow(isAppShow);
						} else {
							//新增数据
							btAuth = new Authority();
							btAuth.setName(btKey);
							btAuth.setResourceName(btName);
							btAuth.setLogRule(ruleName);
							btAuth.setResourceType(Constants.RESOURCE_TYPE_BUTTON);
							btAuth.setResourceStatus(Constants.ENABLED);
							btAuth.setResourceLevel(String.valueOf(level1));
							btAuth.setResourceUrl(btUrl);
							btAuth.setResourceNo(authOrder++);
							btAuth.setCreateTime(new Date());
							btAuth.setAuthority(mdAuth);
							btAuth.setAppShow(isAppShow);
							authorityDao.save(btAuth);
							//授权超级管理员角色
							authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, btAuth.getId());
						}
					}
					//增加自定义按钮
					List<Button> btList = buttonMap.get(md.getKey().toLowerCase());
					if(null!=btList && !btList.isEmpty()) {
						for(Button bt : btList) {
							String btUrl = Constants.RESOURCE_BUTTON_URL + bt.getInWhichPage() + Constants.UNDERLINE 
										+ bt.getFormEntityName() + Constants.UNDERLINE + bt.getKey();
							String btName = bt.getFormCaption() + Constants.MINUS + bt.getCaption();
							String ruleName = btName;
							String btKey = mdKey + Constants.UNDERLINE + bt.getFormKey().toUpperCase() 
										+ Constants.UNDERLINE + bt.getKey().toUpperCase();
							Authority btAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, btUrl, 
									Constants.RESOURCE_TYPE_BUTTON, Constants.ENABLED);
							if(null!=btAuth) {
								btAuth.setResourceName(btName);
								btAuth.setName(btKey);
								btAuth.setLogRule(ruleName);
								btAuth.setResourceNo(authOrder++);
								btAuth.setLastUpdateTime(new Date());
								btAuth.setResourceLevel(String.valueOf(level1));
								btAuth.setAuthority(mdAuth);
								btAuth.setAppShow(isAppShow);
							} else {
								//新增数据
								btAuth = new Authority();
								btAuth.setName(btKey);
								btAuth.setResourceName(btName);
								btAuth.setLogRule(ruleName);
								btAuth.setResourceType(Constants.RESOURCE_TYPE_BUTTON);
								btAuth.setResourceStatus(Constants.ENABLED);
								btAuth.setResourceLevel(String.valueOf(level1));
								btAuth.setResourceUrl(btUrl);
								btAuth.setResourceNo(authOrder++);
								btAuth.setCreateTime(new Date());
								btAuth.setAuthority(mdAuth);
								btAuth.setAppShow(isAppShow);
								authorityDao.save(btAuth);
								//授权超级管理员角色
								authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, btAuth.getId());
							}
						}
					}
					
					//增加数据权限
					String[] rdu = Constants.RESOURCE_DATA_URL;
					for(int i=0,len=rdu.length; i<len; i++) {
						String dataUrl = rdu[i] + Constants.UNDERLINE + entityName;
						String dataName = Constants.RESOURCE_DATA_NAME[i];
						String dataKey = mdKey + Constants.UNDERLINE + Constants.RESOURCE_DATA_KEY[i];
						Authority btAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, dataUrl, 
								Constants.RESOURCE_TYPE_DATA, Constants.ENABLED);
						if(null!=btAuth) {
							btAuth.setResourceName(dataName);
							btAuth.setName(dataKey);
							//btAuth.setResourceUrl(dataUrl);
							btAuth.setLogRule(dataName);
							btAuth.setResourceNo(authOrder++);
							btAuth.setLastUpdateTime(new Date());
							btAuth.setResourceLevel(String.valueOf(level1));
							btAuth.setAuthority(mdAuth);
							btAuth.setAppShow(isAppShow);
						} else {
							//新增数据
							btAuth = new Authority();
							btAuth.setName(dataKey);
							btAuth.setResourceName(dataName);
							btAuth.setLogRule(dataName);
							btAuth.setResourceType(Constants.RESOURCE_TYPE_DATA);
							btAuth.setResourceStatus(Constants.ENABLED);
							btAuth.setResourceLevel(String.valueOf(level1));
							btAuth.setResourceUrl(dataUrl);
							btAuth.setResourceNo(authOrder++);
							btAuth.setCreateTime(new Date());
							btAuth.setAuthority(mdAuth);
							btAuth.setAppShow(isAppShow);
							authorityDao.save(btAuth);
							//授权超级管理员角色
							authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, btAuth.getId());
						}
					}
					//增加字段权限
					List<Form> formList = fieldFormMap.get(md.getKey().toLowerCase());
					if(null!=formList && !formList.isEmpty()) {
						for(Form fr : formList) {
							
							//保存表记录
							String dataUrl = Constants.RESOURCE_FORM_URL + Constants.UNDERLINE
											+ fr.getEntityName();
							String dataName = fr.getCaption();
							String dataKey = Authority.RESOURCE_PREFIX
											+ Constants.RESOURCE_FIELD_KEY + Constants.UNDERLINE 
											+ fr.getKey().toUpperCase();
							Authority frAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, dataUrl, 
									Constants.RESOURCE_TYPE_FIELD, Constants.ENABLED);
							if(null!=frAuth) {
								frAuth.setResourceName(dataName);
								frAuth.setName(dataKey);
								frAuth.setLogRule(dataName);
								frAuth.setResourceNo(authOrder++);
								frAuth.setLastUpdateTime(new Date());
								frAuth.setResourceLevel(String.valueOf(level1));
								frAuth.setAuthority(mdAuth);
								frAuth.setAppShow(isAppShow);
							} else {
								//新增数据
								frAuth = new Authority();
								frAuth.setName(dataKey);
								frAuth.setResourceName(dataName);
								frAuth.setLogRule(dataName);
								frAuth.setResourceType(Constants.RESOURCE_TYPE_FIELD);
								frAuth.setResourceStatus(Constants.ENABLED);
								frAuth.setResourceLevel(String.valueOf(level1));
								frAuth.setResourceUrl(dataUrl);
								frAuth.setResourceNo(authOrder++);
								frAuth.setCreateTime(new Date());
								frAuth.setAuthority(mdAuth);
								frAuth.setAppShow(isAppShow);
								authorityDao.save(frAuth);
								//授权超级管理员角色
								authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, frAuth.getId());
							}
							long level2 = level1 + 1;
							long fieldOrder = 1L;
							List<Field> fieldList = fr.getFieldList();
							if(null!=fieldList && !fieldList.isEmpty()) {
								for(Field fi : fieldList) {
									if(StringUtils.isNotBlank(fi.getKey()) && fi.getEnableFieldAuthCheck()){
										//保存字段记录
										String fdDataUrl = Constants.RESOURCE_FIELD_URL + Constants.UNDERLINE
														+ fr.getEntityName() 
														+ com.qyxx.platform.gsc.utils.Constants.NAME_SPLIT_SYMBOL
														+ fi.getKey();
										String fdDataName = fi.getCaption();
										String fdDataKey = dataKey + Constants.UNDERLINE + fi.getKey().toUpperCase();
										
										//保存可见字段属性
										String fiDataUrl = fdDataUrl + com.qyxx.platform.gsc.utils.Constants.NAME_SPLIT_SYMBOL
														+ Constants.RESOURCE_FIELD_VISIBLE;
										String fiDataName = fdDataName + Constants.RESOURCE_FIELD_VISIBLE_CAPTION;
										String fiDataKey = fdDataKey + Constants.UNDERLINE + Constants.RESOURCE_FIELD_VISIBLE.toUpperCase();
										Authority fiAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, fiDataUrl, 
												Constants.RESOURCE_TYPE_FIELD, Constants.ENABLED);
										if(null!=fiAuth) {
											fiAuth.setResourceName(fiDataName);
											fiAuth.setName(fiDataKey);
											fiAuth.setLogRule(fiDataName);
											fiAuth.setResourceNo(fieldOrder++);
											fiAuth.setLastUpdateTime(new Date());
											fiAuth.setResourceLevel(String.valueOf(level2));
											fiAuth.setAuthority(frAuth);
											frAuth.setAppShow(isAppShow);
										} else {
											//新增数据
											fiAuth = new Authority();
											fiAuth.setName(fiDataKey);
											fiAuth.setResourceName(fiDataName);
											fiAuth.setLogRule(fiDataName);
											fiAuth.setResourceType(Constants.RESOURCE_TYPE_FIELD);
											fiAuth.setResourceStatus(Constants.ENABLED);
											fiAuth.setResourceLevel(String.valueOf(level2));
											fiAuth.setResourceUrl(fiDataUrl);
											fiAuth.setResourceNo(fieldOrder++);
											fiAuth.setCreateTime(new Date());
											fiAuth.setAuthority(frAuth);
											frAuth.setAppShow(isAppShow);
											authorityDao.save(fiAuth);
											//授权超级管理员角色
											authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, fiAuth.getId());
										}
										
										//保存只读字段属性
										String frDataUrl = fdDataUrl + com.qyxx.platform.gsc.utils.Constants.NAME_SPLIT_SYMBOL
														+ Constants.RESOURCE_FIELD_READONLY;
										String frDataName = fdDataName + Constants.RESOURCE_FIELD_READONLY_CAPTION;
										String frDataKey = fdDataKey + Constants.UNDERLINE + Constants.RESOURCE_FIELD_READONLY.toUpperCase();
										Authority firAuth = authorityDao.findUnique(FIND_AUTH_BY_URL_HQL, frDataUrl, 
												Constants.RESOURCE_TYPE_FIELD, Constants.ENABLED);
										if(null!=firAuth) {
											firAuth.setResourceName(frDataName);
											firAuth.setName(frDataKey);
											firAuth.setLogRule(frDataName);
											firAuth.setResourceNo(fieldOrder++);
											firAuth.setLastUpdateTime(new Date());
											firAuth.setResourceLevel(String.valueOf(level2));
											firAuth.setAuthority(frAuth);
											firAuth.setAppShow(isAppShow);
										} else {
											//新增数据
											firAuth = new Authority();
											firAuth.setName(frDataKey);
											firAuth.setResourceName(frDataName);
											firAuth.setLogRule(frDataName);
											firAuth.setResourceType(Constants.RESOURCE_TYPE_FIELD);
											firAuth.setResourceStatus(Constants.ENABLED);
											firAuth.setResourceLevel(String.valueOf(level2));
											firAuth.setResourceUrl(frDataUrl);
											firAuth.setResourceNo(fieldOrder++);
											firAuth.setCreateTime(new Date());
											firAuth.setAuthority(frAuth);
											firAuth.setAppShow(isAppShow);
											authorityDao.save(firAuth);
											//授权超级管理员角色
											authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, firAuth.getId());
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
	}
	
	/**
	 * 根据menu配置文件处理菜单资源
	 * 
	 * @param menu
	 * @param fieldFormMap
	 * @param buttonMap
	 */
	public void handleMenuResource(Menu menu, Map<String, List<Form>> fieldFormMap, Map<String, List<Button>> buttonMap
						, Boolean isFullUpdate, List<String> updatedModules) {		
		List<Business> bsList = menu.getBusiness();
		if(null!=bsList && !bsList.isEmpty()) {
			for(Business bs : bsList) {
				if(com.qyxx.platform.gsc.utils.Constants.MENU_MODULE.equalsIgnoreCase(bs.getKey())) {
					handlePcBusinessResource(bs,fieldFormMap,buttonMap,isFullUpdate,updatedModules);
				}else{
					handleAppBusinessResource(bs,fieldFormMap,buttonMap,isFullUpdate,updatedModules);
				}
			}
		}
		//同步更新权限缓存
		resourceCacheService.refreshResource();
	}
	
	/**
	 * 根据menu-pcbusiness配置文件处理菜单资源
	 * 
	 * @param menu
	 * @param fieldFormMap
	 * @param buttonMap
	 */
	public void handlePcBusinessResource(Business bs, Map<String, List<Form>> fieldFormMap, Map<String, List<Button>> buttonMap
						, Boolean isFullUpdate, List<String> updatedModules) {		

					//业务模块
					List<Modules> mdsList = bs.getModules();
					if(null!=mdsList && !mdsList.isEmpty()) {
						long mdsOrder = 1L;
						for(Modules mds : mdsList) {
							//模块集合或业务字典
							if(Modules.TYPE_MODULES.equalsIgnoreCase(mds.getType()) || Modules.TYPE_DICTS.equalsIgnoreCase(mds.getType())){
								//业务模块集合
								String mdsKey = Authority.RESOURCE_PREFIX + mds.getKey().toUpperCase();
								Authority mdsAuth = authorityDao.findUnique(FIND_AUTH_BY_NAME_HQL, mdsKey, 
										Constants.RESOURCE_TYPE_MENU, Constants.ENABLED, Constants.RESOURCE_LEVEL_1);
								if(null!=mdsAuth) {
									//修改数据
									String mdsName = mds.getName();
									if(!mdsName.equals(mdsAuth.getResourceName())) {
										//修改国际化语言支持
										modifyAuthLocale(mdsAuth.getId(), mdsName, mds.getKey());
									}
									mdsAuth.setResourceName(mds.getName());
									mdsAuth.setResourceNo(mdsOrder++);
									mdsAuth.setResourceIcon(mds.getIconSkin());
									mdsAuth.setLastUpdateTime(new Date());
									mdsAuth.setAppShow(false);
								} else {
									//新增数据
									mdsAuth = new Authority();
									mdsAuth.setName(mdsKey);
									mdsAuth.setResourceName(mds.getName());
									mdsAuth.setLogRule(mds.getName());
									mdsAuth.setResourceType(Constants.RESOURCE_TYPE_MENU);
									mdsAuth.setResourceStatus(Constants.ENABLED);
									mdsAuth.setResourceLevel(Constants.RESOURCE_LEVEL_1);
									mdsAuth.setResourceUrl("");
									mdsAuth.setResourceNo(mdsOrder++);
									mdsAuth.setResourceIcon(mds.getIconSkin());
									mdsAuth.setCreateTime(new Date());
									mdsAuth.setAppShow(false);
									authorityDao.save(mdsAuth);
									//授权超级管理员角色
									authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, mdsAuth.getId());
									//增加国际化语言支持
									saveAuthLocale(mdsAuth, mds.getKey());
								}
								List<Module> mdList = mds.getModule();
							    handleModuleResource(mdList, mdsAuth, fieldFormMap,2, buttonMap, isFullUpdate, updatedModules);
							}
						}
					}
				
			
		
		//同步更新权限缓存
		resourceCacheService.refreshResource();
	}
	
	/**
	 * 根据menu-appbusiness配置文件处理菜单资源
	 * 
	 * @param menu
	 * @param fieldFormMap
	 * @param buttonMap
	 */
	public void handleAppBusinessResource(Business bs, Map<String, List<Form>> fieldFormMap, Map<String, List<Button>> buttonMap
						, Boolean isFullUpdate, List<String> updatedModules) {		

					//业务模块
					List<Modules> mdsList = bs.getModules();
					if(null!=mdsList && !mdsList.isEmpty()) {
						long mdsOrder = 1L;
						for(Modules mds : mdsList) {
							//移动端模块集合
							if(Modules.TYPE_APPS.equalsIgnoreCase(mds.getType()) ) {
								//业务模块集合
								String mdsKey = Authority.RESOURCE_PREFIX + mds.getKey().toUpperCase();
								Authority mdsAuth = authorityDao.findUnique(FIND_AUTH_BY_NAME_HQL, mdsKey, 
										Constants.RESOURCE_TYPE_MENU, Constants.ENABLED, Constants.RESOURCE_LEVEL_1);
								if(null!=mdsAuth) {
									//修改数据
									String mdsName = mds.getName();
									if(!mdsName.equals(mdsAuth.getResourceName())) {
										//修改国际化语言支持
										modifyAuthLocale(mdsAuth.getId(), mdsName, mds.getKey());
									}
									mdsAuth.setResourceName(mds.getName());
									mdsAuth.setResourceNo(mdsOrder++);
									mdsAuth.setResourceIcon(mds.getIconSkin());
									mdsAuth.setLastUpdateTime(new Date());
									mdsAuth.setAppShow(true);
									//mdsAuth.setAppShow(true);
								} else {
									//新增数据
									mdsAuth = new Authority();
									mdsAuth.setName(mdsKey);
									mdsAuth.setResourceName(mds.getName());
									mdsAuth.setLogRule(mds.getName());
									mdsAuth.setResourceType(Constants.RESOURCE_TYPE_MENU);
									mdsAuth.setResourceStatus(Constants.ENABLED);
									mdsAuth.setResourceLevel(Constants.RESOURCE_LEVEL_1);
									mdsAuth.setResourceUrl("");
									mdsAuth.setResourceNo(mdsOrder++);
									mdsAuth.setResourceIcon(mds.getIconSkin());
									mdsAuth.setCreateTime(new Date());
									mdsAuth.setAppShow(true);
									//mdsAuth.setAppShow(true);
									authorityDao.save(mdsAuth);
									//授权超级管理员角色
									authorityDao.save(Constants.SUPER_ADMIN_ROLE_ID, mdsAuth.getId());
									//增加国际化语言支持
									saveAuthLocale(mdsAuth, mds.getKey());
								}
								List<Module> mdList = mds.getModule();
							 handleModuleResource(mdList, mdsAuth, fieldFormMap,2, buttonMap, isFullUpdate, updatedModules);
							
							}
						}
					}
				
			
		
		//同步更新权限缓存
		resourceCacheService.refreshResource();
	}
	
	/**
	 * 保存资源国际化信息
	 * 
	 * @param auth
	 * @param key
	 */
	public void saveAuthLocale(Authority auth, String key) {
		Set<DefinitionEntity> deSet = DefinitionCache.getSet("SYS_LOCALE_DICT", Constants.LOCALE_ZH_CN);
		for(DefinitionEntity de : deSet) {
			AuthorityLocale al = new AuthorityLocale();
			al.setAuthority(auth);
			al.setResourceLocale(de.getValue());
			if(Constants.LOCALE_ZH_CN.equals(al.getResourceLocale())) {
				al.setResourceName(auth.getResourceName());//默认中文
			} else if(Constants.LOCALE_ZH_TW.equals(al.getResourceLocale())) {
				al.setResourceName(FontConvertUtils.toLong(auth.getResourceName()));//转繁体中文
			} else if(Constants.LOCALE_EN.equals(al.getResourceLocale())) {
				al.setResourceName(EncodeUtils.toLowerOrUpperCaseFirstChar(key, false));
			} else {
				al.setResourceName(auth.getResourceName());//默认中文
			}
			authorityLocaleDao.save(al);
		}
		/*AuthorityLocale al1 = new AuthorityLocale();
		al1.setAuthority(auth);
		al1.setResourceLocale(Constants.LOCALE_ZH_CN);
		al1.setResourceName(auth.getResourceName());//默认中文
		authorityLocaleDao.save(al1);
		AuthorityLocale al2 = new AuthorityLocale();
		al2.setAuthority(auth);
		al2.setResourceLocale(Constants.LOCALE_ZH_TW);
		al2.setResourceName(FontConvertUtils.toLong(auth.getResourceName()));//转繁体中文
		authorityLocaleDao.save(al2);
		AuthorityLocale al3 = new AuthorityLocale();
		al3.setAuthority(auth);
		al3.setResourceLocale(Constants.LOCALE_EN);//英文
		al3.setResourceName(EncodeUtils.toLowerOrUpperCaseFirstChar(key, false));
		authorityLocaleDao.save(al3);*/
	}
	
	/**
	 * 修改资源国际化信息
	 * 
	 * @param auth
	 * @param key
	 */
	public void modifyAuthLocale(Long authId, String name, String key) {
		List<AuthorityLocale> alList = authorityLocaleDao.findBy("authority.id", authId);
		if(null!=alList && !alList.isEmpty()) {
			for(AuthorityLocale al : alList) {
				if(Constants.LOCALE_ZH_CN.equals(al.getResourceLocale())) {
					al.setResourceName(name);
				} else if(Constants.LOCALE_ZH_TW.equals(al.getResourceLocale())) {
					al.setResourceName(FontConvertUtils.toLong(name));
				} else if(Constants.LOCALE_EN.equals(al.getResourceLocale())) {
					al.setResourceName(key);
				} else {
					al.setResourceName(name);
				}
				//authorityLocaleDao.save(al);
			}
		}
	}

	/**
	 * 根据用户查找对应的app菜单资源
	 * 
	 * @param userId
	 * @return
	 */
	public List<ResourceJson> findAppMenuResource(Long userId,
			String locale) {
		List<Object> paramList = Lists.newArrayList();
		paramList.add(userId);
//		paramList.add(Constants.RESOURCE_LEVEL_1);
//		paramList.add(Constants.RESOURCE_LEVEL_2);
//		paramList.add(Constants.RESOURCE_LEVEL_3);
		paramList.add(Constants.RESOURCE_TYPE_MENU);
		paramList.add(locale);
		paramList.add(Constants.ENABLED);
		paramList.add(true);
		List<ResourceJson> list = authorityLocaleDao.find(
				FIND_APP_MENU_HQL, paramList.toArray());

		// 去除重复项
		Set<ResourceJson> set = new HashSet<ResourceJson>();
		List<ResourceJson> newList = new ArrayList<ResourceJson>();
		Map<Long, ResourceJson> tmpMap = new HashMap<Long, ResourceJson>();
		
		for (Iterator<ResourceJson> iter = list.iterator(); iter
				.hasNext();) {
			ResourceJson element = iter.next();
			if (set.add(element)) {
				newList.add(element);
				tmpMap.put(element.getId(), element);
			}
		}
		list.clear();
		list.addAll(newList);

		Map<Long, ResourceJson> map = new HashMap<Long, ResourceJson>();
		if (null != list) {
			for (ResourceJson rj : list) {
				if (rj.getParentId() == null) {
					map.put(rj.getId(), rj);
				} else {
					ResourceJson t = tmpMap.get(rj.getParentId());
					if (t != null) {
						t.getChilds().add(rj);
					}
				}
			}
		}
		List<ResourceJson> rjList = new ArrayList<ResourceJson>(
				map.values());
		Collections.sort(rjList, new Comparator<ResourceJson>() {

			public int compare(ResourceJson o1, ResourceJson o2) {
				if (o1.getResourceNo() > o2.getResourceNo()) {
					return 1;
				} else if (o1.getResourceNo() < o2.getResourceNo()) {
					return -1;
				} else {
					return 0;
				}
			}
		});
		return rjList;
	}

	public List<String> findAppResourceUrl(Long id) {		
		List<String> rsUrlList =  authorityDao.findSingleValueBySQL(FIND_RESOURCE_URL_BY_SQL, id);		
		return rsUrlList;
	}
}
